﻿namespace Summoner
{
    using UnityEngine;
    using System.Collections.Generic;

    public class GameObjectPool : PoolBase<GameObject>
    {
        private Queue<GameObject> _pool;
        private GameObject _prefab;

        public override void Init(GameObject prefab)
        {
            this._pool = new Queue<GameObject>();
            this._prefab = prefab;
            this._prefab.SetActive(false);
        }

        public override GameObject Instantiate(bool poolOnly)
        {
            GameObject obj;
            if ((this._pool.Count == 0) || poolOnly)
            {
                obj = Object.Instantiate(this._prefab) as GameObject;
                if ((obj != null) && poolOnly)
                {
                    obj.SetActive(false);
                    this._pool.Enqueue(obj);
                }
                return obj;
            }
            else
            {
                obj = this._pool.Dequeue();
                if(obj == null)
                {
                    this.RemoveAllPooled();
                    obj = Object.Instantiate(this._prefab) as GameObject;
                }
                obj.transform.SetParent(null);
                obj.SetActive(true);
                return obj;
            }
        }

        public override void Recycle(GameObject obj)
        {
            base.Recycle(obj);
            obj.SetActive(false);
        }

        public override void RemoveOne()
        {
            GameObject go = this.Pool.Dequeue();
            go.transform.SetParent(null);
            Object.Destroy(go);
        }

        public override void RemoveAllPooled()
        {
            while(this.Pool.Count > 0)
            {
                GameObject go = this.Pool.Dequeue();
                go.transform.SetParent(null);
                Object.Destroy(go);
            }
        }

        public override void End()
        {
            this.RemoveAllPooled();
            if (!AssetPath.IsEditor) { Object.Destroy(this.Prefab); }
            this.Prefab = null;
        }

        protected override void Dispose(bool disposing)
        {
            this.End();
            base.Dispose(disposing);
        }

        public override Queue<GameObject> Pool { get { return this._pool; } }

        public override int Count
        {
            get
            {
                return base.Count;
            }
        }

        public override GameObject Prefab
        {
            get
            {
                return base.Prefab;
            }
            set
            {
                base.Prefab = value;
            }
        }
    }
}